<?php

namespace App\Http\Controllers\Api;

use App\Activity;
use App\Demands;
use App\Http\Services\FileManager;
use App\Http\Services\UserManager;
use App\Message;
use App\MessageRemind;
use App\MessageXUser;
use App\User;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class MessageController extends Controller
{
    /**
     * 获取消息列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMessageList(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $type = !is_null($request->get('type')) ? $request->get('type') : 'demand';
        $limit         = !is_null($request->get('limit')) ? $request->get('limit') : 8;
        $page          = !is_null($request->get('page')) ? $request->get('page') : 1;

        $pageInfo = [
            'limit' => $limit,
            'page' => $page,
        ];

        /** @var Message $message */
        if($type == 'demand'){
            $messageList = Message::whereType('demand')->whereToUserId($user->id);

            $pageInfo['total'] = $messageList->count();
            $message_ids=$messageList->pluck('id')->toArray();
            //TODO 清除消息提醒
            MessageRemind::whereUserId($user->id)->whereIn('message_id',$message_ids)->forceDelete();

            $messageList = $messageList->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();
        }elseif($type == 'activity'){
            $messageList = Message::whereType('activity')->whereToUserId($user->id);

            $pageInfo['total'] = $messageList->count();
            //TODO 清除消息提醒
            $message_ids=$messageList->pluck('id')->toArray();
            MessageRemind::whereUserId($user->id)->whereIn('message_id',$message_ids)->forceDelete();
            $messageList = $messageList->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();
        }elseif($type == 'system'){
            $messageIds = MessageXUser::whereUserId($user->id)->pluck('message_id');

            $messageList = Message::whereIn('id',$messageIds)->orWhere(function ($where){
                $where->whereType('system')->whereSystemMessageType(0);
            });

            $pageInfo['total'] = $messageList->count();
            //TODO 清除消息提醒
            $message_ids=$messageList->pluck('id')->toArray();
            MessageRemind::whereUserId($user->id)->whereIn('message_id',$message_ids)->forceDelete();

            $messageList = $messageList->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();
        }else{
            return response()->json(['level' => 'error','message' => '消息类型不正确']);
        }

        if(count($messageList) > 0){
            foreach($messageList as $message){
                if ($message->img_id!=0)
                    $message->img_url = FileManager::getImgUrl($message->img_id);
                else
                    $message->img_url = '';
                $content=htmlspecialchars_decode($message->detail);
                $content=str_replace(" ","",$content);
                $content=strip_tags($content);
                if ($content)
                    $message->is_detail=1;
                else
                    $message->is_detail=0;
                if ($type=='demand'){
                        if ($message->title=='恭喜你，对接成功'){
                            $message->color='#00C735';
                        } else if ($message->title=='很遗憾，您的对接请求已被拒绝'){
                            $message->color='#DF3636';
                        }else
                            $message->color= '#3782FF';
                }
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $messageList]);
    }

    public function getMessageDetail(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $id=$request->get('id');
        $message = Message::whereId($id)->first();
        if (!$message)
            return response()->json(['level' => 'error','message' => '该消息不存在','data' => []]);
        if ($message->type!='system'){
            if ($message->to_user_id != $user->id)
                return response()->json(['level'=>'error','message'=>'无权查看','data'=>[]]);
        }
        return response()->json(['level'=>'success','message'=>'获取成功','data'=>$message]);
    }

    public function getMyMessageRemind(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level'=>'success','data'=>0]);
        $message_exist=MessageRemind::whereUserId($user->id)->first();

        if ($message_exist)
            return response()->json(['level'=>'success','data'=>1]);
        else
            return response()->json(['level'=>'success','data'=>0]);
    }

    public function getMyMessageNumber(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);
        $message_unread_ids=MessageRemind::whereUserId($user->id)->pluck('message_id')->toArray();
        if (count($message_unread_ids)> 0){
            $demand_message = Message::whereIn('id',$message_unread_ids)->whereToUserId($user->id)->whereType('demand')->count();
            $system_message = Message::whereIn('id',$message_unread_ids)->whereType('system')->count();
        } else {
            $demand_message = 0;
            $system_message = 0;
        }
        $result=[
            'system_message'=>$system_message,
            'demand_message'=>$demand_message
        ];
            return response()->json(['level'=>'success','data'=>$result]);
    }

}
